*************************************************
*			01_empirical_results				*
*												*
*	This do file runs code produce the main		* 
*	figures from for the empirical results		*
*   in Ricks ® Kay "Time-Limited Subsidies"		*
*												*
*												*
*												*
*************************************************



* prepare 
clear all
set more off, perm
cap log close

/* packages (uncomment if needed)

* Install ftools (remove program if it existed previously)
cap ado uninstall ftools
net install ftools, from("https://raw.githubusercontent.com/sergiocorreia/ftools/master/src/")

* Install reghdfe 6.x
cap ado uninstall reghdfe
net install reghdfe, from("https://raw.githubusercontent.com/sergiocorreia/reghdfe/master/src/")

*/

***
* Set Macros Here
***

* set directory (change for your machine)
global wind 	"/Users/michaeldavidricks/Documents/timelimits_replication"

* Make results/temp directories
cap mkdir "${wind}/results"
cap mkdir "${wind}/temp"

* Set colors for graphs
global ptb5 "54 75 154"
global ptb4 "74 123 183"
global ptb3 "110 166 205"
global ptb1 "194 228 239"
global ptr3 "246 126 75"
global ptr5 "165 0 38"

* Set font for graphs 
*		(only uncomment this line if you have the font installed)
*graph set window fontface "CMU Serif"



****
** MAIN ANALYSIS: Figures 1 and 2 
**
****


clear all
use "${wind}/data_final/analysis_data.dta", replace

* Drop non-PTC firms
drop if flag_1603==1
drop if any_repower==1


*********** 
* Sun Abraham ES Code *
*********** 


drop if count<=24
egen state_time  = group(year month state)
egen fac_month  = group(facilityid month)
gen netgen_zero = netgen==0
gen all = 1

* Number for calculating means
bys facilityid: gegen max_count = max(count)



* Inidicators over all event and cohort pairs

forval j = 2002/2021 {
  forval i = 61/180 {
    qui count if count==`i' &vintage==`j'	
    if `r(N)' >0 {
	  gen e`i'_c`j' = count==`i' &vintage==`j'	
	}
  }
  gen emin_c`j' = count<=60 & vintage==`j'
  qui count if count>180 & vintage==`j'
  if `r(N)'>0 {
  gen emax_c`j' = count>180 & vintage==`j'
  }
}

* Omitted groups
drop e120*



* Run Analysis on Main Outcomes
do "${wind}/code/analyze/sun_ab_ado.do"  "capacity_factor netgen netgen_zero" "" "e61_c2002-emin_c2021" "facilityid state_time" "facilityid month"


* Export regression results to table
putexcel set "${wind}/results/new_tables.xlsx", open modify


putexcel B4 = "Capacity Factor"
putexcel C4 = "Net Generation (MWh)"
putexcel D4 = "Exit: $\mathds{1}(\text{Net Generation}=0)$"

putexcel A5 = "Overall Effect"
putexcel A7 = "Short-Term (Years 11-12)"
putexcel A9 = "Long-Term (Years 13-15)"

forval i = 1/3 {
	local j = 2*`i' +3
	local k = 2*`i' +4

	* Capacity Factor
	putexcel B`j' = matrix(betas[1,`i']) , nformat( 0.00)
	putexcel B`k' = matrix(ses[1,`i']), nformat( "("0.00")")

	* Net Generation
	putexcel C`j' = matrix(betas[2,`i']) , nformat( 000)
	putexcel C`k' = matrix(ses[2,`i']), nformat( "("000")")

	* No Generation
	putexcel D`j' = matrix(betas[3,`i']) , nformat( 0.0000)
	putexcel D`k' = matrix(ses[3,`i']), nformat( "("0.0000")")
}




* Means
putexcel A12 = "Average in Year 10"
sum netgen if inrange(count, 109,120) & max_count>=132
putexcel B12 = "`r(mean)'"
sum netgen_zero if inrange(count, 109,120) & max_count>=132
putexcel C12 = "`r(mean)'"
sum capacity_factor if inrange(count, 109,120) & max_count>=132
putexcel D12 = "`r(mean)'"



putexcel A16 = "\textbf{Panel B: Heterogeneity by Vintage}"
putexcel B16 = "2002-2006"
putexcel C16 = "2007-2008"
putexcel D16 = "2009-2010"

putexcel A17 = "Short-Term (Years 11-12)"


* Heterogeneous Cuts (Capacity Factor)
putexcel B17 = matrix(beta_het[1,2]) , nformat( 0.00)
putexcel B18 = matrix(se_het[1,2]), nformat( "("0.00")")

putexcel C17 = matrix(beta_het[1,3]) , nformat( 0.00)
putexcel C18= matrix(se_het[1,3]), nformat( "("0.00")")

putexcel D17 = matrix(beta_het[1,4]) , nformat( 0.00)
putexcel D18 = matrix(se_het[1,4]), nformat( "("0.00")")


* Means
putexcel A20 = "Average in Year 10"
sum netgen if inrange(count, 109,120) & max_count>=132 & inrange(vintage,2002,2006)
putexcel B20 = "`r(mean)'"
sum netgen_zero if inrange(count, 109,120) & max_count>=132 & inrange(vintage,2007,2008)
putexcel C20 = "`r(mean)'"
sum capacity_factor if inrange(count, 109,120) & max_count>=132& inrange(vintage,2009,2010)
putexcel D20 = "`r(mean)'"


putexcel close


* Count firms in sample
count if count==25

* Count firms after deadline
count if count==121

***
* Make Event Study Figure
***

* Locals for the figure
local b_short : di  %3.2f betas[1,2]
local se_short : di  %3.2f ses[1,2]
local b_long : di  %3.2f betas[1,3]
local se_long : di  %3.2f ses[1,3]

* Get mean outcome
sum capacity_factor if inrange(count, 109,120) & max_count>=132
local av: di  %3.1f `r(mean)'

* Make Labels
foreach t in 1.96 2.58 3.29 {
	if abs(betas[1,2]/ses[1,2]) > `t'{
		local b_short = "`b_short'{superscript:*}"
	}
	if abs(betas[1,3]/ses[1,3]) > `t'{
		local b_long = "`b_long'{superscript:*}"
	}
}
di "`b_long'"

* Save ES Coefs (just in case)
preserve
clear
svmat ES_pool
keep ES_pool1-ES_pool4
ren (*) (count beta ub lb)
drop if count==.

save "${wind}/data_final/ES_pool.dta", replace

* Make the ES Figure	
	
tw  (pci -8 120 2 120, lcolor(black%10) lp(longdash)) ///
	(pci -8 144 2 144, lcolor(black%10) lp(longdash)) ///
	(rarea ub lb count, color("${ptb1}") ) ///
	(pci 0 60 0 180, lcolor(black%60)) ///
    (connected beta count, lc("${ptb4}") mc("${ptb4}") mfc(white) msize(1)) /// 
	(pcarrowi -3.1 115.5 -.25 115.5, lcolor(black) lp(solid) mcolor(black)) 	///
	(pci -3.1 115.5 -3.1 114, lcolor(black) lp(solid) ) 	///
    , ylab(-8(2)4 , format(%2.1f) angle(0) nogrid labsize(med)) ///
	yscale(r(-8 4)) xlab(60 "5" 72 "6" 84 "7" 96 "8" 108 "9" 120 "10" 132 "11" 144 "12" 156 "13" 168 "14" 180 "15", labsize(med) nogrid) ///
	xtitle(" " "Year of Reported Production (End of Year)", size(medlarge)) ytitle("Change in Capacity Factor" " ", size(medlarge)) ///
	xsize(9) graphregion(color(white)) legend( order(5 "Cohort Average Effect (Sun & Abraham 2021)") pos(6) region(lcolor(black)))  ///
	plotregion(margin(0)) ///
 	text(3. 134.25 "Short-Term Effect:" , place(9) height(28pt) alignment(top) justification(right)) text(3. 134.25 "`b_short'" "(`se_short')", place(3) height(28pt) alignment(top))  ///
	text(3. 168 "Long-Term Effect:", place(9) height(28pt) alignment(top)) text(3. 168  "`b_long'" "(`se_long')  ", place(3) height(28pt) alignment(top)) ///
	text(-3 87 "Average Capacity Factor in Year 10:  `av'")
	

* Export Graph	
graph export "${wind}/results/es_plot.pdf", replace
	
restore


******
**  Figure 2 Forgone WInd
**
******


* Make list of counterfactual dates
preserve
clear
set obs 528
gen simulation_date = _n+503
format simulation_date %tm
tempfile temp
save `temp'

* Cross data with dates them
use "${wind}/data_final/analysis_data.dta", replace
drop if flag_1603==1|any_repower==1
keep if count ==1 
keep facilityid date 
ren date first_date
cross using `temp'
sort facilityid simulation_date
drop if simulation_date<first_date
gen count = simulation_date+1-first_date


* Calculate Foregone Wind (beta(2) is the netgen result from above)
gen forgone_sq = 0
replace forgone_sq = -betas[2,2] if count>120 & count<145
replace forgone_sq = -betas[2,3] if count>=145 & count<=300

**
* Counterfactual with 15-Year Time Limit
**

gen forgone_15 = 0

* Already forgone
replace forgone_15 = -betas[2,2] if count>120 & count<145 & simulation_date <=743
replace forgone_15 = -betas[2,3] if count>=145 & count<=300 & simulation_date <=743

* Change if deadline of 15 starting 2022
replace forgone_15 = -betas[2,2] if count>180 & count<205 & simulation_date >743
replace forgone_15 = -betas[2,3] if count>=205 & count<=300 & simulation_date >743


**
* Counterfactual with 20-Year Time Limit
**

gen forgone_20 = 0

* Already forgone
replace forgone_20 = -betas[2,2] if count>120 & count<145 & simulation_date <=743
replace forgone_20 = -betas[2,3] if count>=145 & count<=300 & simulation_date <=743

* Change if deadline of 15 starting 2022
replace forgone_20 = -betas[2,2] if count>240 & count<245 & simulation_date >743
replace forgone_20 = -betas[2,3] if count>=245 & count<=300 & simulation_date >743


***
* Combine for Figure
***

* Collapse and Sum
gcollapse (sum) forgone*, by(simulation_date)
sort simulation_date
foreach v in sq 15 20 {
  gen cummulative_`v' = sum(forgone_`v')/1000
}


* Make the Line Plot

tw 	(line cummulative_15 simulation_date, lw(.6) lp (-)lcolor("${ptr3}")) ///
	(line cummulative_20 simulation_date, lw(.6) lp(_.) lcolor("${ptb3}")) ///
	(line cummulative_sq simulation_date, lw(.6) lcolor("${ptb5}"))  ///
	if simulation_date>=540, xtitle(" " "Year", size(large)) ytitle("Cummulative Forgone" "Production (GWh)" " ", size(large))  ///
	xlab(540 "2005" 600 "2010" 660 "2015" 720 "2020" 780 "2025" 840 "2030" 900 "2035" 960 "2040" 1020 "2045", labsize(medlarge) nogrid) ///
	ylab(0 "0" 50000 "50,000" 100000 "100,000" 150000 "150,000"  200000  "200,000", angle(0) nogrid) ///
	legend(order(3 "Status Quo (10-Year)" 1 "Change to 15-Year" 2 "Change to 20-Year") row(1) size(medlarge) pos(6) region(lcolor(black))) ///
	graphregion(color(white) lw(1)) xsize(9)
	
graph export "${wind}/results/lost_generation.pdf", replace

noi sum if _n==_N

restore



******
**  Appendix Table: Robustnesses
**
******







*** 1603 Placebo


use "${wind}/data_final/analysis_data.dta", replace
recode flag_1603 .=0

* Drop Repowered firms
drop if any_repower==1
drop if count<=24
egen state_time  = group(year month state)
gen all = 1

bys facilityid: gegen max_count = max(count)


* Over all event and cohort pairs
forval x = 0/1{
forval j = 2002/2021 {
  forval i = 61/180 {
    qui count if count==`i' &vintage==`j' & 	flag_1603==`x'
    if `r(N)' >0 {
	  gen e`i'_c`j'_f`x' = count==`i' &vintage==`j'& 	flag_1603==`x'
	}
  }
  qui count if count<=60 & vintage==`j'& flag_1603==`x'
  if `r(N)'>0 {
    gen emin_c`j'_f`x' = count<=60 & vintage==`j'& 	flag_1603==`x'
  }
  qui count if count>180 & vintage==`j'& 	flag_1603==`x'
  if `r(N)'>0 {
    gen emax_c`j'_f`x' = count>180 & vintage==`j'& 	flag_1603==`x'
  }
}
}

* Omitted Group
drop e120*

* Sun and Abraham
do "${wind}/code/analyze/sun_ab_ado.do"  "capacity_factor" "flag_1603" "e61_c2002_f0-emin_c2013_f1" "facilityid state_time" "facilityid month"


* Export regression results to Table
putexcel set "${wind}/results/new_tables.xlsx", open modify
forval i = 2/2 {
  local j = 2*`i' +21
  local k = 2*`i' +22

  * Capacity Factor ()
  putexcel B`j' = matrix(betas[1,`i'+3]) , nformat( 0.00)
  putexcel B`k' = matrix(ses[1,`i'+3]), nformat( "("0.00")")
}


putexcel A22 = "\textbf{Panel C: Effect Heterogeneity}"
putexcel B22 = "1603 Firms (Placebo)"


putexcel A30 = "Average in Year 10"

sum capacity_factor if inrange(count, 109,120) & max_count>=132 & flag_1603==1

putexcel B30 = "`r(mean)'"

putexcel close


*** Prices


use "${wind}/data_final/analysis_data.dta", replace

* Drop 
drop if any_repower==1
drop if flag_1603==1
drop if count<=24
egen state_time  = group(year month state)
gen all = 1


bys facilityid: gegen max_count = max(count)

sum capacity_factor if inrange(count, 109,120) & max_count>=132 & high_price==0
sum capacity_factor if inrange(count, 109,120) & max_count>=132 & high_price==1


* Over all event and cohort pairs
forval x = 0/1{
forval j = 2002/2021 {
  forval i = 61/180 {
    qui count if count==`i' &vintage==`j' & 	high_price==`x'
    if `r(N)' >0 {
	  gen e`i'_c`j'_f`x' = count==`i' &vintage==`j'& 	high_price==`x'
	}
  }
  qui count if count<=60 & vintage==`j'& high_price==`x'
  if `r(N)'>0 {
    gen emin_c`j'_f`x' = count<=60 & vintage==`j'& 	high_price==`x'
  }
  qui count if count>180 & vintage==`j'& 	high_price==`x'
  if `r(N)'>0 {
    gen emax_c`j'_f`x' = count>180 & vintage==`j'& 	high_price==`x'
  }
}
}

* Omitted Group
drop e120*

* Sun and Abraham
do "${wind}/code/analyze/sun_ab_ado.do"  "capacity_factor" "high_price" "e61_c2002_f0-emin_c2019_f1" "facilityid state_time" "facilityid month"

putexcel set "${wind}/results/new_tables.xlsx", open modify
forval i = 1/3 {
  local j = 2*`i' +21
  local k = 2*`i' +22

  * Capacity Factor - Low Price
  putexcel C`j' = matrix(betas[1,`i']) , nformat( 0.00)
  putexcel C`k' = matrix(ses[1,`i']), nformat( "("0.00")")

  * Capacity Factor - High Price
  putexcel D`j' = matrix(betas[1,`i'+3]) , nformat( 0.00)
  putexcel D`k' = matrix(ses[1,`i'+3]), nformat( "("0.00")")
}

putexcel C22 = "Low Price"
putexcel D22 = "High Price"

sum capacity_factor if inrange(count, 109,120) & max_count>=132 & high_price==0
putexcel C30 = `r(mean)'
sum capacity_factor if inrange(count, 109,120) & max_count>=132 & high_price==1
putexcel D30 = `r(mean)'

putexcel close

mat list betas
mat list ses


